package com.atguigu.yygh.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.R;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.utils.ConstantPropertiesUtil;
import com.atguigu.yygh.user.utils.HttpClientUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Api(description = "微信登录接口")
@Controller
@RequestMapping("/api/ucenter/wx")
public class WeixinApiController {


    @Autowired
    private UserInfoService userInfoService;

    /**
     * 获取微信登录参数
     */
    @ApiOperation(value = "微信登录获取二维码")
    @GetMapping("getLoginParam")
    @ResponseBody
    public R genQrConnect(HttpSession session) throws UnsupportedEncodingException {
        //安装api文档， 整理回调地址
        String redirectUri = URLEncoder.encode(
                ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL, "UTF-8");
        Map<String, Object> map = new HashMap<>();

        map.put("appid", ConstantPropertiesUtil.WX_OPEN_APP_ID);
        map.put("redirectUri", redirectUri);
        map.put("scope", "snsapi_login");
        map.put("state", System.currentTimeMillis() + "");//System.currentTimeMillis()+""

        return R.ok().data(map);
    }

    //微信登录回调
    @ApiOperation(value = "微信登录回调方法")
    @GetMapping("callback")
    public String callback(String code, String state, HttpSession session) {
        //1获得code微信验证码
        System.out.println("code = " + code);
        System.out.println("state = " + state);
        //2拿code请求到微信固定地址获取参数，access_token,openid
        //方案一直接拼写url：
        // https://api.weixin.qq.com/sns/oauth2/access_token?
        // appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        //2.1方案二：创建基础url，参数使用占位符，之后放入参数
        //  %s   占位符
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                code
        );

        try {
            //2.2使用工具 发送请求
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println("accessTokenInfo = " + accessTokenInfo);
            //2.3解析字符串
            JSONObject jsonObject = JSONObject.parseObject(accessTokenInfo);
            String access_token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");
            //3.据openid查询用户信息
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("openid", openid);
            UserInfo userInfo = userInfoService.getOne(wrapper);
            //4.用户信息为空 走注册步骤
            if (userInfo == null) {
                //4.1根据openid访问微信，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
                String resultInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("resultInfo:" + resultInfo);
                JSONObject resultUserInfoJson = JSONObject.parseObject(resultInfo);
                //解析用户信息
                //用户昵称
                String nickname = resultUserInfoJson.getString("nickname");
                //用户头像
                String headimgurl = resultUserInfoJson.getString("headimgurl");
                //4.2获取扫描人信息 添加数据库

                userInfo = new UserInfo();
                userInfo.setNickName(nickname);
                userInfo.setOpenid(openid);
                userInfo.setStatus(1);
                userInfoService.save(userInfo);
            }
            //5用户信息不为空 ，走登录
            //5.1创建map 存入返回的name
            Map<String, Object> map = new HashMap<>();
            String name = userInfo.getName();
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);

            //5.2判断userInfo是否有手机号,如果手机号为空 返回openid
            //如果手机号不为空 ，还是返回openid但是值为空字符串
            //前端进行判断  如果openid不为空 则需要绑定手机号 如果openid不为空 不需要绑定

            if (StringUtils.isEmpty(userInfo.getPhone())) {
                map.put("openid", userInfo.getOpenid());
            } else {
                map.put("openid", "");
            }
            //5.3使用jwt生成token
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token", token);
            //直接跳转到前端页面
            return "redirect:http://localhost:3000/weixin/callback?token="
                    + map.get("token") + "&openid=" + map.get("openid")
                    + "&name=" + URLEncoder.encode((String) map.get("name"), "utf-8");

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }


    }
}
